next();

function next() {
    setTimeout(getUrl, 1000);
}

var last_url;
var port = chrome.extension.connect();
port.onMessage.addListener(get_msg);

function getUrl() {
    new_url = window.location.href;

    if (last_url != new_url) {
        last_url = new_url;	
        port.postMessage({ "command": "url_change", "url": new_url });
		pageload();
	}

    next();
}

function pageload() {
	shiftstate = false;
	document.addEventListener('keydown', shiftkey);

	if (document && document.forms) {
		for (i = 0; i < document.forms.length; i++) {
			f = document.forms[i];
			f.addEventListener('submit', formsubmit);
			for (j = 0; j < f.length; j++) {
				f[j].addEventListener('focus', formfocus);
			}
		}
	}
}

function shiftkey(event) {
	shiftstate = event.shiftKey;
}

function formfocus(event) {
	lastform = event.target;	
}

function formsubmit(event) {
	if (shiftstate && event && event.target) {
		post_form(event.target);
	}
}

function valueof(ele) {
	if (ele) {
		if (( ( ele.tagName == 'INPUT') && ele.type.match(/text|password/i) )) {
			return escape(ele.value);	
		} else if (ele.tagName == 'SELECT' ) {

		}		
	}

	return null;
}

function post_form(f) {
	fname = prompt("Create New Login", location.host);
	if (fname) {
		port.postMessage({ "command": "save_form", "data": save_form(f), "fn": fname, "url": window.location.href });
	}
}

function save_form(f) {
	if ( f && (f.tagName == 'FORM'))  {
		var arr = [];
		for (j = 0; j < f.length; j++) {
			var fval = valueof(f[j]);
			if (fval) {
				arr.push(f[j].name + '=' + fval);
			}			
		}

		return arr.join('&');
	}

	return '';
}

function get_msg(msg) {
	if (msg.command == 'fillform') {
		get_data(msg.message);
	} else if (msg.command == 'saveform') {
		save_last_form();
	} else if (msg.command == 'alert') {
		alert(msg.msg);
	} 
}

function save_last_form() {
	if (lastform) {
		for (i = 0; i = 100; i++ ) {
			if(lastform.tagName == 'FORM') {
				break;
			} else {
				lastform = lastform.parentNode;
			}
		}
		
		post_form(lastform);
	}
}

function get_data(data) {
    if (data) {
        var strings = data.split("\n");
        for (var i = 0; i < strings.length; i++) {
            var keypair = strings[i].split('=');
            if (keypair[0] != 'url') {
                for (j = 0; j < document.forms.length; j++) {
                    form = document.forms[j];
                    for (k = 0; k < form.elements.length; k++) {
                        element = form.elements[k];

						if (element) {
							if (element.name.toLowerCase() == keypair[0].toLowerCase()) {
								element.value = rtrim(keypair[1]);
	                        }
						}
                    }
                }
            }
        }
    }
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
